import _ from 'lodash'
import React, { ReactNode } from 'react'
import { notification, Button } from 'antd'
import { AxiosRequestConfig } from 'axios'
import { uaaApp, ITableWatermark } from '..'

interface IUdConfigProvider {
  /** 请求相关 */
  http: {
    /** 使用 Rpc 包装格式 */
    useRpcWrap: boolean
    /** 使用 */
    useBizErrorHandler: boolean
    useSysErrorHandler: boolean
    /** 错误提示方法 */
    errorTip: (tip: { message?: string | ReactNode, description?: string | ReactNode }) => void
    /** 设置token到请求中 */
    requestBeforeSetToken: (config: AxiosRequestConfig) => AxiosRequestConfig
    /** 请求发出前 */
    requestBefore: (config: AxiosRequestConfig) => AxiosRequestConfig
    /** 失败时的处理函数 */
    errorHandler: {
      [key in (string | number)]: ((error: any) => void)
    }
  },
  /** 授权相关 */
  auth: {
    canUse?: (key: string) => boolean
  },
  api: {
    /** 请求分页数据时，是否把条件放到 conditions 字段中 */
    useConditionsField: boolean
  },
  ui: {
    getPageContainer: () => Window | HTMLElement,
    table: {
      watermark: ITableWatermark
    }
  }
}

/** 配置服务 */
let udConfigProvider: IUdConfigProvider = {

  http: {
    useRpcWrap: true,
    useBizErrorHandler: true,
    useSysErrorHandler: true,

    errorTip: (tip: { message?: string | ReactNode, description?: string | ReactNode }) => {
      let args = _.extend({}, { message: '系统提示' }, tip) as any
      notification.error(args)
    },
    requestBeforeSetToken: (config: AxiosRequestConfig): AxiosRequestConfig => {
      let token = uaaApp.getToken()
      if (token) {
        config.headers = {
          'Authorization': token.accessToken,
          ...config.headers
        }
      }
      return config
    },
    requestBefore: (config: AxiosRequestConfig): AxiosRequestConfig => { return config },

    /** 失败时的处理函数 */
    errorHandler: {
      request: (error) => {
        let func = _.get(error, 'config.errorTip', udConfigProvider.http.errorTip)
        func({ message: '请求失败', description: error })
      },
      400: (error: any) => {
        error.config.errorTip({
          message: '错误的请求',
          description: _.get(error, 'response.data.msg', error.statusText)
        })
      },
      401: (error: any) => {
        notification.error({
          message: '登录超时',
          description: <div style={{ display: 'flex', alignItems: 'center' }}>
            <span style={{ flex: '1' }}>请点击退出按钮后重新登录。</span>
            <Button type="primary" style={{ fontSize: '12px' }} size="small" onClick={() => {
              uaaApp.signOut()
            }}>退出</Button>
          </div>,
          onClose: () => {
            uaaApp.signOut()
          },  
        })
      },
      403: (error: any) => {
        error.config.errorTip({ message: '没有权限', description: '你的账号没有该操作的权限' })
      },
      404: (error: any) => {
        error.config.errorTip({ description: '请求的资源不存在' })
      },
      500: (error: any) => {
        // 服务器500，且请求体里code:12004为登录超时
        if (_.get(error,'response.data.code')===12004) {
          const errorHandle = udConfigProvider.http.errorHandler[401]
          errorHandle(error)
          return
        }
        let msg = _.get(error, 'response.data.data.msg', _.get(error, 'response.data.msg', '系统错误，请稍后重试！'))
        if (error.data) {
          // 非服务器错误接口code:500情况
          msg = _.get(error, 'data.data.msg', _.get(error, 'data.msg', '系统错误，请稍后重试！'))
        }
        error.config.errorTip({ description: msg })
      },
      other: (error: any) => {
        let msg = '系统错误，请稍后重试！'
        if (error.message == 'Network Error') {
          msg = '网络异常，请检查你的网络。'
        } else {
          if (process.env.NODE_ENV == 'development') {
            msg = error.message
          }
        }
        error.config.errorTip({ description: msg })
      }
    }
  },
  auth: {
    canUse: null
  },
  api: {
    useConditionsField: true
  },
  ui: {
    getPageContainer: () => {
      return document.querySelector<HTMLElement>('.ud-main-content') || window
    },
    table: {
      watermark: {
        enable: false,
        color: '#000',
        opacity: 0.06,
        fontSize: 18,
        angle: -25,
        text: () => {
          let info = uaaApp.getSysInfo()
          return info ? info.profile.id : ''
        },
        width: 80,
        height: 50,
        x: 10,
        y: 25
      }
    }
  }
}

export { udConfigProvider } 
